<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 邀请返利业务逻辑
 */
class InviteReward extends LogicBase
{
    /**
     * 获取邀请奖励数据搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 邀请人ID搜索
        !empty($data['inviter_id']) && $where['inviter_id'] = $data['inviter_id'];
        
        // 奖励类型搜索
        !empty($data['type']) && $where['type'] = $data['type'];
        
        // 积分范围搜索
        if (isset($data['min_points']) && $data['min_points'] !== '') {
            $where['points'] = ['>=', $data['min_points']];
        }
        if (isset($data['max_points']) && $data['max_points'] !== '') {
            if (isset($where['points'])) {
                $where['points'] = ['between', [$data['min_points'], $data['max_points']]];
            } else {
                $where['points'] = ['<=', $data['max_points']];
            }
        }
        
        // 搜索条件：用户昵称
        !empty($data['search_data']) && $where['nickname'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 获取邀请收益统计
     */
    public function getInviteStats($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        
        if (!$userId) {
            return null;
        }
        
        // 获取用户信息
        $user = $this->modelUser->getInfo(['id' => $userId]);
        if (!$user) {
            return null;
        }
        
        // 邀请人数统计
        $inviteCount = $this->modelUser->stat(['inviter_id' => $userId], 'count');
        
        // 今日邀请人数
        $todayStart = strtotime(date('Y-m-d'));
        $todayInviteCount = $this->modelUser->stat([
            'inviter_id' => $userId,
            'create_time' => ['>=', $todayStart]
        ], 'count');
        
        // 本月邀请人数
        $monthStart = strtotime(date('Y-m-01'));
        $monthInviteCount = $this->modelUser->stat([
            'inviter_id' => $userId,
            'create_time' => ['>=', $monthStart]
        ], 'count');
        
        // 邀请奖励统计
        $totalReward = $this->modelPointsRecord->stat([
            'user_id' => $userId,
            'type' => 'invite_reward'
        ], 'sum', 'points') ?: 0;
        
        // 今日奖励
        $todayReward = $this->modelPointsRecord->stat([
            'user_id' => $userId,
            'type' => 'invite_reward',
            'create_time' => ['>=', $todayStart]
        ], 'sum', 'points') ?: 0;
        
        // 本月奖励
        $monthReward = $this->modelPointsRecord->stat([
            'user_id' => $userId,
            'type' => 'invite_reward',
            'create_time' => ['>=', $monthStart]
        ], 'sum', 'points') ?: 0;
        
        // 可提现余额（假设积分可以提现）
        $withdrawableBalance = $user['total_points'] ?? 0;
        
        $stats = [
            'invite_code' => $user['invite_code'],
            'total_invites' => $inviteCount,
            'today_invites' => $todayInviteCount,
            'month_invites' => $monthInviteCount,
            'total_reward' => $totalReward,
            'today_reward' => $todayReward,
            'month_reward' => $monthReward,
            'withdrawable_balance' => $withdrawableBalance,
            'invite_url' => $this->generateInviteUrl($user['invite_code'])
        ];
        
        return $stats;
    }
    
    /**
     * 获取邀请记录
     */
    public function getInviteRecords($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 20;
        $type = $data['type'] ?? 'all'; // all: 全部, today: 今日, month: 本月
        
        if (!$userId) {
            return null;
        }
        
        // 构建查询条件
        $where = ['inviter_id' => $userId];
        
        if ($type == 'today') {
            $todayStart = strtotime(date('Y-m-d'));
            $where['create_time'] = ['>=', $todayStart];
        } elseif ($type == 'month') {
            $monthStart = strtotime(date('Y-m-01'));
            $where['create_time'] = ['>=', $monthStart];
        }
        
        $list = $this->modelUser->getList($where, 
            'id,nickname,avatar_url,create_time', 
            'create_time desc', 
            [
                'list_rows' => $limit,
                'page' => $page
            ]
        );
        
        if ($list && !empty($list)) {
            foreach ($list as $key => $item) {
                $item['register_time_text'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['reward_points'] = 10; // 假设每邀请一人奖励10积分
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
        }
        
        return $list;
    }
    
    /**
     * 生成邀请链接
     */
    private function generateInviteUrl($inviteCode)
    {
        // 这里应该根据实际的小程序页面路径生成
        $baseUrl = '';
        return $baseUrl . '/pages/index/index?invite_code=' . $inviteCode;
    }
    
    /**
     * 处理邀请奖励
     */
    public function processInviteReward($inviterId, $inviteeId)
    {
        if (!$inviterId || !$inviteeId) {
            return [RESULT_ERROR, '参数错误'];
        }
        
        // 检查邀请者
        $inviter = $this->modelUser->getInfo(['id' => $inviterId]);
        if (!$inviter) {
            return [RESULT_ERROR, '邀请者不存在'];
        }
        
        // 检查被邀请者
        $invitee = $this->modelUser->getInfo(['id' => $inviteeId]);
        if (!$invitee) {
            return [RESULT_ERROR, '被邀请者不存在'];
        }
        
        // 邀请奖励配置
        $inviteRewardPoints = 10; // 邀请奖励积分
        $registerRewardPoints = 5; // 注册奖励积分
        
        try {
            // 开启事务
            \think\facade\Db::transaction(function () use ($inviterId, $inviteeId, $inviter, $invitee, $inviteRewardPoints, $registerRewardPoints) {
                
                // 给邀请者奖励
                $this->modelUser->updateInfo(['id' => $inviterId], [
                    'total_points' => ['inc', $inviteRewardPoints],
                    'update_time' => time()
                ]);
                
                // 记录邀请者积分
                $this->modelPointsRecord->insertGetId([
                    'user_id' => $inviterId,
                    'type' => 'invite_reward',
                    'points' => $inviteRewardPoints,
                    'description' => '邀请用户注册奖励',
                    'create_time' => time(),
                    'update_time' => time()
                ]);
                
                // 给被邀请者注册奖励
                $this->modelUser->updateInfo(['id' => $inviteeId], [
                    'total_points' => ['inc', $registerRewardPoints],
                    'update_time' => time()
                ]);
                
                // 记录被邀请者积分
                $this->modelPointsRecord->insertGetId([
                    'user_id' => $inviteeId,
                    'type' => 'register_reward',
                    'points' => $registerRewardPoints,
                    'description' => '新用户注册奖励',
                    'create_time' => time(),
                    'update_time' => time()
                ]);
                
                // 发送消息通知邀请者
                $this->modelMessage->insertGetId([
                    'user_id' => $inviterId,
                    'type' => 'invite_reward',
                    'title' => '邀请奖励',
                    'content' => "恭喜您成功邀请用户「{$invitee['nickname']}」注册，获得{$inviteRewardPoints}积分奖励！",
                    'is_read' => 0,
                    'create_time' => time(),
                    'update_time' => time()
                ]);
                
                // 发送消息通知被邀请者
                $this->modelMessage->insertGetId([
                    'user_id' => $inviteeId,
                    'type' => 'register_reward',
                    'title' => '注册奖励',
                    'content' => "欢迎加入亦通查！您获得了{$registerRewardPoints}积分新用户奖励！",
                    'is_read' => 0,
                    'create_time' => time(),
                    'update_time' => time()
                ]);
            });
            
            return [RESULT_SUCCESS, '邀请奖励处理成功'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('处理邀请奖励失败：' . $e->getMessage());
            return [RESULT_ERROR, '邀请奖励处理失败'];
        }
    }
    
    /**
     * 获取邀请规则说明
     */
    public function getInviteRules()
    {
        $rules = [
            [
                'title' => '邀请奖励',
                'content' => '成功邀请一位新用户注册，您可获得10积分奖励'
            ],
            [
                'title' => '新用户奖励',
                'content' => '通过邀请链接注册的新用户可获得5积分注册奖励'
            ],
            [
                'title' => '积分用途',
                'content' => '积分可用于兑换优惠券、参与抽奖活动等'
            ],
            [
                'title' => '提现规则',
                'content' => '积分暂不支持直接提现，后续会开放积分商城功能'
            ]
        ];
        
        return [RESULT_SUCCESS, '获取邀请规则成功', $rules];
    }
    
    /**
     * 验证邀请码
     */
    public function validateInviteCode($inviteCode)
    {
        if (empty($inviteCode)) {
            return [RESULT_ERROR, '邀请码不能为空'];
        }
        
        $inviter = $this->modelUser->getInfo(['invite_code' => $inviteCode, 'status' => 1]);
        
        if (!$inviter) {
            return [RESULT_ERROR, '邀请码无效'];
        }
        
        return [RESULT_SUCCESS, '邀请码有效', $inviter];
    }
}